package com.ruoyi.system.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.ruoyi.system.domain.UploadData;
import com.ruoyi.system.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

@Service
@Slf4j
public class UploadImpl implements UploadService {

    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

    @Value("${aliyun.upload.accessKey}")
    private String aliyunUploadAccessKey;

    @Value("${aliyun.upload.securityKey}")
    private String aliyunUploadSecurityKey;

    @Value("${aliyun.upload.endpoint}")
    private String aliyunUploadEndpoint;

    @Value("${aliyun.upload.bucketName}")
    private String aliyunUploadBucketName;

    @Override
    public String uploadImageToCtYun(UploadData build) {
        OSS ossClient = new OSSClientBuilder().build(aliyunUploadEndpoint, aliyunUploadAccessKey, aliyunUploadSecurityKey);
        String fileName = getFilePath(build.getFileOriginName());
        try {
            OSS oss = buildOss();
            // 设置文件权限为公共读
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setHeader(OSSHeaders.OSS_OBJECT_ACL, CannedAccessControlList.PublicRead);

            // 上传图片
            oss.putObject(aliyunUploadBucketName, fileName, build.getInputStream(), objectMetadata);
            return "https://" + aliyunUploadBucketName + "." + aliyunUploadEndpoint + "/" + fileName;
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getMessage());
        } catch (Throwable e) {
            log.error("upload failed", e);
        } finally {
            ossClient.shutdown();
        }
        return null;
    }

    /**
     * 获取文件保存路径
     *
     * @param fileOriginName 用户上传文件名
     * @return 文件保存路径
     */
    private String getFilePath(String fileOriginName) {
        String fileType = "jpg";
        if (!StringUtils.isEmpty(fileOriginName) && fileOriginName.contains(".")) {
            fileType = fileOriginName.substring(fileOriginName.lastIndexOf(".") + 1);
        }
        String fileName = System.currentTimeMillis() + "." + fileType;
        String date = simpleDateFormat.format(Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")).getTime());
        return date + "/" + fileName;
    }

    private OSS buildOss() {
        return new OSSClientBuilder().build(aliyunUploadEndpoint, aliyunUploadAccessKey, aliyunUploadSecurityKey);
    }
}
